package com.jinlejia.erp.ui.new_house.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.ActivitySelectHousesBinding;
import com.jinlejia.erp.ui.new_house.adapter.SelecHousesAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.SharePTool;
import com.jinlejia.erp.utils.StringUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class SelectHousesActivity extends AppCompatActivity implements YfLoadMoreListener {


    private SelecHousesAdapter adapter;
    private int page = 1;
    private String keywords = "";
    private boolean mLoadingLock = false;

    private ActivitySelectHousesBinding binding;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_select_houses);
        initViews();
        initEvents();
        initData();
    }

    protected void initViews() {

        binding.recyclerView.setHasFixedSize(true);
        binding.recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        ArrayList<Map<String, String>> dataList = new ArrayList<>();
        adapter = new SelecHousesAdapter(dataList);
        binding.recyclerView.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.recyclerView.enableAutoLoadMore(this);
    }

    protected void initData() {
        OkHttpUtils.get().url(ApiConfig.NEWHOUSE_LIST)
                .addParams("pageSize", "15")
                .addParams("pageIndex", StringUtil.valueOf(page))
                .addParams("city", SharePTool.getCity(this))
                .addParams("keywords", keywords)
                .build().execute(new MapCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                call.cancel();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Map<String, Object> response, int id) {
                ArrayList<Map<String, String>> dataList = new ArrayList<>();
                if (DataFilter.filter(SelectHousesActivity.this, response, adapter)) {
                    JSONObject data = JSON.parseObject(response.get("data").toString());
//                    ArrayList<Map<String, String>> dataList = JSON.parseObject(data.getJSONArray("page").toJSONString(), new TypeReference<ArrayList<Map<String, String>>>() {
//                    });
                    JSONArray pageArray = data.getJSONArray("page");
                    for (int i = 0, j = pageArray.size(); i < j; i++) {
                        JSONObject object = (JSONObject) pageArray.get(i);
                        Map<String, String> map = new HashMap<>();
                        map.put("code", object.getString("houseCode"));
                        map.put("name", object.getString("houseName"));
                        map.put("commissionStr", object.get("commissionStr").toString());
                        map.put("commissionType", object.get("commissionType").toString());
                        map.put("lat", object.get("latitude").toString());
                        map.put("lng", object.get("longitude").toString());
                        dataList.add(map);
                    }
                    if (page == 1) {
                        adapter.setData(dataList);
                    } else {
                        if (dataList.size() > 0) {
                            adapter.addData(dataList);
                        } else {
                            page--;
                        }
                    }
                }
                mLoadingLock = false;
            }
        });

    }

    protected void initEvents() {
        binding.idBack.setOnClickListener(this::onClick);
        binding.idConfirm.setOnClickListener(this::onClick);
        binding.idSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                keywords = s.toString();
                initData();
            }
        });
        adapter.setOnItemClickListener((view, o) -> adapter.addChecked((Map<String, String>) o));
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_back:
                //返回
                finish();
                break;
            case R.id.id_confirm:
                //确定
                ArrayList<Map<String, String>> selectMap = adapter.getSelectMap();
                if (selectMap.size()>0){
                    Intent intent = new Intent();
                    intent.putExtra("data",selectMap);
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        mLoadingLock = true;
        page++;
        initData();
    }
}
